<?php

namespace app\admin\controller;

use app\common\Helper;
use app\admin\model\Ticket as TicketMdl;
use app\admin\model\Store;

use think\Db;
use think\Exception;
use think\Request;

/**
 * 优惠券
 */
class Ticket extends Base
{

    public function _initialize()
    {
        parent::_initialize();

        $this->model = new TicketMdl();
    }

    /**
     * 列表
     */
    public function getList(){
        $param = self::getHttpParam();
        $start = 0;
        $length = 20;

        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        //$defaultWhere = $this->getDefaultWhere();
        $defaultWhere = [];
        $defaultWhere['a.status'] = ['neq', 3];
        //$defaultWhere['a.endTime'] = ['gt', date('Y-m-d H:i:s')];
        $where = $defaultWhere;
        if($this->admin->roleType != 1){
            $where['s.province'] = $this->admin->province;
            if($this->admin->city != '所有') {
                $where['s.city'] = $this->admin->city;
            }
        }
        if (isset($param->type) && $param->type != '') {
            if (!in_array($param->type, [1, 2])) {
                return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 格式不正确');
            }
            if($param->type == 1){
                // 免费领取
                $where['a.getMethod'] = 0;
            }else{
                // 付费购买
                $where['a.getMethod'] = 3;
            }
        }
        if (isset($param->status) && $param->status != '') {
            if (!in_array($param->status, [1, 2, 3])) {
                return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'status 格式不正确');
            }
            if($param->status == 1){
                // 上架
                $where['a.status'] = 5;
            }elseif ($param->status == 2){
                // 下架
                $where['a.status'] = 4;
            }else{
                // 已过期
                $where['a.endTime'] = ['lt', date('Y-m-d H:i:s')];
            }
        }
        if (isset($param->storeName)) {
            $where['s.name'] = ['like', '%' . $param->storeName . '%'];
        }
        $model = $this->model;
        $order = 'a.create_time DESC';
        $join = [
            ['store s', 's.id = a.storeId'],
        ];
        $field = 'a.id, a.specialOfferStatement, a.backgroundImg, a.buyTicketMoney, a.getMethod, a.status, a.endTime, s.name as storeName, a.name as specialOfferName';
        $result = $model->alias('a')->where($where)->join($join)->limit($start, $length)->order($order)->field($field)->select();
        $total = $model->alias('a')->where($where)->join($join)->count();

        if (!$result) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '没有相关优惠券');
        }

        foreach ($result as $item) {
            if($item['endTime'] < date('Y-m-d H:i:s')){
                $item['status'] = 2;
                $model->where('id', $item['id'])->update(['status' => 2]);
            }
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result, $total);
    }

    /**
     * 详情
     */
    public function detail(){
        $param = self::getHttpParam();
        $model = $this->model;

        if (empty($param->ticketId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'ticketId 不能这空');
        }

        $id = $param->ticketId;
        $where = [
            'a.id' => $id
        ];
        $join = [
            ['store s', 's.id = a.storeId'],
        ];
        $fields = 'a.*, s.name as storeName, s.province, s.city, s.area, s.details, s.address, s.addressNumb, s.businessHours, a.name as specialOfferName';
        $item = $model->alias('a')->where($where)->join($join)->field($fields)->find();

        if (empty($item)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到相关优惠券');
        } else {
            return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $item);
        }
    }

    /**
     * 上架/下架
     */
    public function handleShelf(){
        $param = self::getHttpParam();
        $model = $this->model;

        if (empty($param->ticketId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'ticketId 不能为空');
        }
        if (empty($param->type)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 不能为空');
        }
        if (!in_array($param->type, [1, 2])) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 格式不正确');
        }

        $id = $param->ticketId;
        $info = $model->where('id', $id)->find();
        if($param->type == 1){
            // 判断店铺是否是上架状态
            $storeInfo = Store::where('id', $info['storeId'])->find();
            if($storeInfo['status'] != 1){
                return show(config('status.ERROR_STATUS'), self::MSG_ERROR, '店铺审核未通过或已下架');
            }
            // 上架
            $data['status'] = 5;
            $result = $model->allowField(true)->save($data, ['id' => $id]);
        }else{
            // 下架
            $data['status'] = 4;
            $result = $model->allowField(true)->save($data, ['id' => $id]);
        }

        if($result !== false){
            return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, '操作成功');
        }else{
            return show(config('status.ERROR_STATUS'), self::MSG_ERROR, $model->getError());
        }
    }

}